<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="5" style="margin-bottom: 10px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>个人信息</span>
          </div>
          <div>
            <ul class="user-info">
              <li><div style="height: 100%"><i class="el-icon-view"></i> 登录账号<div class="user-right">{{ user.username }}</div></div></li>
              <li><i class="el-icon-user"></i> 用户名称 <div class="user-right">{{ user.first_name }}</div></li>
              <li><i class="el-icon-discount"></i> 用户工号 <div class="user-right">{{ user.job_no }}</div></li>
              <li><i class="el-icon-phone"></i> 手机号码 <div class="user-right">{{ user.phone }}</div></li>
              <li><i class="el-icon-share"></i> 用户邮箱 <div class="user-right">{{ user.email }}</div></li>
              <li><i class="el-icon-monitor"></i> 所属部门 <div class="user-right"> {{ user.department_name }}</div></li>
              <li>
                <i class="el-icon-lock"></i> 安全设置
                <div class="user-right">
                  <a @click="$refs.pass.dialog = true">修改密码</a>
                  <a @click="$refs.email.dialog = true">修改邮箱</a>
                </div>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="16" :lg="18" :xl="19">
        <!--    用户资料    -->
        <el-card class="box-card">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="用户资料" name="first">
              <el-form ref="form" :model="form" :rules="rules" style="margin-top: 10px;" size="small" label-width="80px">
                <el-form-item label="用户名称" prop="first_name">
                  <el-input v-model="form.first_name" style="width: 35%" />
                  <span style="color: #C0C0C0;margin-left: 10px;">用户名称不作为登录使用</span>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="form.phone" style="width: 35%;" />
                  <span style="color: #C0C0C0;margin-left: 10px;">手机号码不能重复</span>
                </el-form-item>
                <el-form-item label="">
                  <el-button :loading="saveLoading" size="mini" type="primary" @click="doSubmit">保存配置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="职称修改" name="second">
              <el-form ref="form" style="margin-top: 10px;" size="small" label-width="80px">
                <el-form-item label="职称名称">
                  <el-select v-model="jobTitle" filterable allow-create class="select" size="small" placeholder="请选择职称">
                    <el-option v-for="(item,index) in labelsList" :label="item.name" :value="item.id" :key="index"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="">
                  <el-button :loading="saveLoading" size="mini" type="primary" @click="handleUpdateJobTitle">保存修改</el-button>
                </el-form-item>
              </el-form>
            <!--    操作日志    -->
            <!-- <el-tab-pane label="操作日志" name="second">
              <el-table v-loading="loading" :data="data" style="width: 100%;">
                <el-table-column prop="description" label="行为" />
                <el-table-column prop="requestIp" label="IP" />
                <el-table-column :show-overflow-tooltip="true" prop="address" label="IP来源" />
                <el-table-column prop="browser" label="浏览器" />
                <el-table-column prop="time" label="请求耗时" align="center">
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.time <= 300">{{ scope.row.time }}ms</el-tag>
                    <el-tag v-else-if="scope.row.time <= 1000" type="warning">{{ scope.row.time }}ms</el-tag>
                    <el-tag v-else type="danger">{{ scope.row.time }}ms</el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  align="right"
                >
                  <template slot="header">
                    <div style="display:inline-block;float: right;cursor: pointer" @click="init">创建日期<i class="el-icon-refresh" style="margin-left: 40px" /></div>
                  </template>
                  <template slot-scope="scope">
                    <span>{{ scope.row.createTime }}</span>
                  </template>
                </el-table-column>
              </el-table> -->
              <!--分页组件-->
              <!-- <el-pagination
                :total="total"
                :current-page="page + 1"
                style="margin-top: 8px;"
                layout="total, prev, pager, next, sizes"
                @size-change="sizeChange"
                @current-change="pageChange"
              /> -->
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
    <updateEmail ref="email" :email="user.email" :userId="user.id" @updateInfo="updateInfo"/>
    <updatePass ref="pass" :userId="user.id"/>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getInfo, getUserLabel, patchUpdateUser } from '@/api/user.js'
import { isvalidPhone } from '@/utils/validate'
import updatePass from './center/updatePass'
import updateEmail from './center/updateEmail'
export default {
  name: 'Center',
  components: { updatePass, updateEmail },
  data() {
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      activeName: 'first',
      saveLoading: false,
      form: {},
      user: {
        email: '',
        id: ''
      },
      labelsList: [],
      jobTitle: null, // 职称
      rules: {
        first_name: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, trigger: 'blur', validator: validPhone }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'id'
    ])
  },
  created() {
    this.requestUserInfo()
    this.requestLabels()
  },
  methods: {
    // 更新个人信息
    updateInfo(){
      this.requestUserInfo()
    },
    // 请求个人信息
    requestUserInfo(){
      getInfo(this.id).then(
        res =>{
          this.user = res.data
          const { label } = this.user
          this.jobTitle = label
        }
      )
    },
    // 请求职称列表
    requestLabels() {
      getUserLabel().then(res => {
        this.labelsList = res.data.results
      })
    },
    handleClick(tab, event) {
      if (tab.name === 'second') {
        this.init()
      }
    },
    // 更新职称信息
    handleUpdateJobTitle() {
      this.saveLoading = true
      const {name} = this.labelsList.find(item => item.id === this.jobTitle) || {}
      let label = name ||　this.jobTitle
      
      patchUpdateUser(this.user.id, {label_name: label}).then(async () => {
        this.$notify({
          title: '提示',
          message: '用户职称修改成功',
          type: 'success',
          duration: 1500
        })
        this.saveLoading = false
      })
      .catch(error =>{
        this.saveLoading = false
      })
    },
    // 保存设置
     doSubmit() {
      if (this.$refs['form']) {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.saveLoading = true
            patchUpdateUser(this.user.id, this.form).then(async () => {
              this.$notify({
                title: '提示',
                message: '用户个人信息修改成功',
                type: 'success',
                duration: 1500
              })
              await this.$store.dispatch('user/getInfo')
              this.requestUserInfo()
              this.saveLoading = false
            })
            .catch(error =>{
              this.saveLoading = false
                if (error.response) {
                  const result = error.response.data
                  Object.keys(result).forEach(
                      key =>{
                        // this.$message.error(result[key][0])
                      }
                    )
                } 
              })
          }
        })
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  .avatar-uploader-icon {
    font-size: 28px;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center
  }

  .avatar {
    width: 120px;
    height: 120px;
    display: block;
    border-radius: 50%
  }
  .user-info {
    padding-left: 0;
    list-style: none;
    li{
      border-bottom: 1px solid #F0F3F4;
      padding: 11px 0;
      font-size: 13px;
    }
    .user-right {
      float: right;

      a{
        color: #317EF3;
      }
    }
  }
</style>
